package javaCode.chapter13.homework;

import java.util.HashSet;
import java.util.Objects;

/**
 * @author 徐州城
 * @version 1.0
 */
@SuppressWarnings("all")
public class Homework06 {
    public static void main(String[] args) {
        //已知：Person类按照id和name重写了HashCode和equals方法，问下面代码输出什么？
        HashSet set = new HashSet();
        Person_ p1 = new Person_(1001, "AA");
        Person_ p2 = new Person_(1002, "BB");
        set.add(p1); //ok
        set.add(p2); //ok
        p1.name = "CC";
        set.remove(p1); //找不到hash值对应的位置
        System.out.println(set); //

        set.add(new Person_(1001,"CC"));
        System.out.println(set);
//
        set.add(new Person_(1001,"AA"));
        System.out.println(set);
    }
}

class Person_{
    String name;
    int id;

    public Person_( int id, String name) {
        this.name = name;
        this.id = id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person_ person_ = (Person_) o;
        return id == person_.id &&
                Objects.equals(name, person_.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, id);
    }

    @Override
    public String toString() {
        return "Person_{" +
                "name='" + name + '\'' +
                ", id=" + id +
                '}';
    }
}